Match (effect)
ちょっと使ってみてるが、やや筋悪な気がしてるmrsekut.icon
discriminated unionの判定が甘い
_tagというkeyにしか対応してない
普通にswtich文を書いたほうが、簡素で安全
Completion
pipeの一番最後に書くやつmrsekut.icon
結果を Option型でラップ
フォールバック(else的な役割)を定義
code:ts
Match.orElse(() => "default")
otherwise的なmrsekut.icon
orElseAbsurd
matcherを作る
雑に言えば、型 or 値のどっちで分岐するか宣言するようなものmrsekut.icon
typeTags
valueTags
Defining patterns
フィールドが特定の prefix で始まるかどうかをマッチングできる
code:ts
import { Match, pipe } from "effect"
const match = pipe(
Match.type<{ type: "A" } | { type: "B" } | { type: "A.A" } | {}>(),
Match.discriminatorStartsWith("type")("A", (_) => 1 as const),
Match.discriminatorStartsWith("type")("B", (_) => 2 as const),
Match.orElse((_) => 3 as const)
)
console.log(match({ type: "A" })) // 1
console.log(match({ type: "B" })) // 2
console.log(match({ type: "A.A" })) // 1
かなり使うタイミングが限られそうmrsekut.icon
逆に、特定の値に一致しないときの処理:
code:ts
Match.not("hi", () => "ok")
tagStartsWith
tags
tagsExhaustive
値やプロパティの一致、関数による条件分岐:
code:ts
Match.when({ age: 18 }, () => "You can vote")
Match.when({ age: (a) => a > 18 }, (u) => Age: ${u.age})
複数条件を満たした時
Predicates
any
bigint
boolean
date
defined
instanceOf
instanceOfUnsafe
is
nonEmptyString
null
number
record
string
symbol
undefined
Built-in Predicates(型判定関数)
Match.string, Match.number, Match.boolean
Match.is("foo", 123):リテラル値一致
Match.instanceOf(Error):インスタンスチェック
Match.defined:null/undefined 以外
自作の型にもできないんかな?mrsekut.icon